#include "TimelineChart.h"
#include <QVBoxLayout>
#include <QScrollArea>
#include <QLabel>
#include <QDebug>
Timeline::Timeline(QWidget *parent)
    : QFrame{parent},
      eventSpacing(30),
      topMargin(20)
{
    // 去掉外框
    setFrameStyle(QFrame::NoFrame);
    setStyleSheet("background: rgba(255, 255, 255, 0);");  // 设置背景透明
}

void Timeline::addEvent(const QString &time, const QString &description, const QString &remaining)
{
    events.append({time, description, remaining});

    // 仅在事件数量发生变化时调整控件大小
    if (events.size() >= 1) {
        updateSize();  // 初始化大小
    }
    update(); // 触发重绘
}

QSize Timeline::sizeHint() const
{
    // 根据事件数量动态调整高度
    int totalHeight = topMargin + events.size() * eventSpacing;
    return QSize(width(), totalHeight);
}

void Timeline::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    int lineX = 50;

    // 绘制主线条
    if (!events.isEmpty()) {
        int lineEndY = topMargin + (events.size() - 1) * eventSpacing;
        painter.setPen(QPen(QColor(217, 220, 220), 2));
        painter.drawLine(lineX, topMargin, lineX, lineEndY);
    }

    // Calculate the scale factor for font size based on widget height
    qreal scaleFactor = width() / 600.0;  // Adjust 500 to the reference height for your design
    int baseFontSize = 10;  // Base font size
    int dynamicFontSize = baseFontSize * scaleFactor;  // Dynamically scaled font size

    // Adjust font size based on widget size
    QFont font("Tahoma", dynamicFontSize, 45);
    painter.setFont(font);
    // 设置列宽（例如：时间、描述、剩余时间）
    int timeColumnWidth = 50;  // 时间列宽
    int descriptionColumnWidth = 150;  // 描述列宽
    int remainingColumnWidth = 80;  // 剩余时间列宽
    // 绘制事件节点和内容
    for (int i = 0; i < events.size(); ++i) {


        int nodeY = topMargin + i * eventSpacing;

        // 节点（圆形）绘制
        painter.setBrush(QBrush(Qt::white));  // 设置圆的填充颜色为蓝色
        painter.setPen(QPen(QColor(87, 205, 255), 4));
        painter.drawEllipse(QPointF(lineX, nodeY), 6, 6);  // Draw the filled circle

        // 设置文本颜色
        painter.setPen(QColor(145, 145, 145));

        // 计算每列的X坐标，确保文本对齐
        int timeX = lineX + 20;  // 时间列开始位置
        int descriptionX = timeX + timeColumnWidth;  // 描述列开始位置
        int remainingX = descriptionX + descriptionColumnWidth;  // 剩余时间列开始位置

        // 绘制时间文本
        QString timeText = QString("%1").arg(events[i].time);
        painter.drawText(timeX, nodeY - dynamicFontSize , timeColumnWidth, dynamicFontSize*3, Qt::AlignLeft, timeText);

        // 绘制描述文本
        QString descriptionText = QString("%1").arg(events[i].description);
        painter.drawText(descriptionX, nodeY - dynamicFontSize , descriptionColumnWidth, dynamicFontSize*3, Qt::AlignLeft, descriptionText);

        // 绘制剩余时间文本
        QString remainingText = QString("%1").arg(events[i].remaining);
        painter.drawText(remainingX, nodeY - dynamicFontSize , remainingColumnWidth, dynamicFontSize*3, Qt::AlignLeft, remainingText);
    }
}

TimelineChart::TimelineChart(QWidget *parent)
    : QWidget(parent),
      m_pTimeline(new Timeline(this)),
      scrollArea(new QScrollArea(this)),
      m_pTimer(new QTimer(this)),
      m_countdown(0)
{
    setObjectName("TimelineChart");
    setWindowFlags(Qt::FramelessWindowHint);  // 设置窗口无边框
    // 设置定时器每秒更新
    connect(m_pTimer, &QTimer::timeout, [this]() {
        // 每秒更新倒计时
        if (m_countdown > 0) {
            m_countdown -= 1000;  // 每秒减少1000毫秒
            // 更新倒计时显示（可以根据需求调整显示方式）
            // 例如，可以调用 getTimeline()->update() 来刷新显示
        }
    });

    // 设置布局
    initializeLayout();

    // 设置默认窗口尺寸
    setWindowSize(600, 400);
}

TimelineChart::~TimelineChart()
{

}

void TimelineChart::configureScrollArea()
{
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 禁用水平滚动条
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);      // 根据需要显示垂直滚动条
    //scrollArea->setWidgetResizable(true);  // 使得子控件自适应
    scrollArea->setStyleSheet("QScrollArea { "
                              "border: none; "
                              "background-color: #ffffff; }");
    scrollArea->setWidgetResizable(false);  // 使得子控件自适应，自动显示滚动条
    scrollArea->setWidget(m_pTimeline);   // 将 m_pTimeline 设置为滚动区域的子控件
}

void TimelineChart::setWindowSize(int width, int height)
{
    m_pTimeline->setEventSpacing(height/7);
    // 设置滚动区域的大小（如果需要固定大小）
    scrollArea->setFixedSize(width, height);  // 或者使用 setMinimumSize() 设置最小大小
    // 设置 m_pTimeline 的大小（可以使用 setFixedSize() 或者 adjustSize()）
    m_pTimeline->setMinimumSize(width, height);  // 设置 m_pTimeline 的固定大小
    resize(width, height);  // 调整窗口的大小
}

// 清除所有事件
void TimelineChart::clearEvents()
{
    if (m_pTimeline) {
        m_pTimeline->clearEvents();  // 假设 Timeline 类有清除事件的功能
    }
}

void TimelineChart::addEvent(const QString &eventDescription)
{
    // 获取当前时间戳
    int currentTime = QDateTime::currentSecsSinceEpoch();

    // 计算剩余时间（假设事件时间为 10 秒后）
    int eventTimestamp = currentTime + 10; // 假设事件发生时间是当前时间的10秒后
    QString remainingTime = calculateRemainingTime();

    // 创建事件对象
    TimelineEvent event;
    event.time = QDateTime::currentDateTime().toString("hh:mm");
    event.description = eventDescription;
    event.remaining = remainingTime;

    // 添加事件到时间轴
    addEvent(event);
}

void TimelineChart::addEvents(const QVector<QString> &eventDescriptions)
{
    for (const QString& eventDescription : eventDescriptions) {
        addEvent(eventDescription);  // 每个事件通过描述添加
    }
}

// 添加单个事件
void TimelineChart::addEvent(const TimelineEvent &event)
{
    if (m_pTimeline) {
        m_pTimeline->addEvent(event.time, event.description, event.remaining);
    }
}

// 添加多个事件
void TimelineChart::addEvents(const QVector<TimelineEvent> &events)
{
    if (events.isEmpty() || !m_pTimeline) {
        return;
    }

    // 使用范围-based for 循环遍历并添加事件
    for (const auto &event : events) {
        m_pTimeline->addEvent(event.time, event.description, event.remaining);
    }
}

// 获取当前的时间轴控件
Timeline *TimelineChart::getTimeline() const
{
    return m_pTimeline;
}

void TimelineChart::setCountdown(int milliseconds)
{
    m_countdown = milliseconds;
    m_startTime = QDateTime::currentDateTime();
    m_pTimer->start(1000);  // 每秒触发一次
}

void TimelineChart::setStartTime()
{
    m_startTime = QDateTime::currentDateTime();
}

// 动态设置滚动区域的显示策略
void TimelineChart::setScrollAreaPolicy(Qt::ScrollBarPolicy horizontalPolicy, Qt::ScrollBarPolicy verticalPolicy)
{
    scrollArea->setHorizontalScrollBarPolicy(horizontalPolicy);
    scrollArea->setVerticalScrollBarPolicy(verticalPolicy);
}

void TimelineChart::initializeLayout()
{
    auto layout = new QVBoxLayout(this);

    // 设置整个TimelineChart控件的边框
       this->setStyleSheet("#TimelineChart { "
                            "border: 1px solid #919191; "
                            "padding: 10px; "
                            "background-color: #ffffff; "
                            "}");
    // 配置滚动区域
    configureScrollArea();
    QLabel* title = new QLabel("时间轴",this);

    QFont font("幼圆", 12, 45);
    font.setBold(true);

    title->setFont(font);
    // 设置标题的边框
    title->setStyleSheet("QLabel { "
                         "border: none; "
                         "color:#919191"
                         "background-color: #ffffff; "
                         "padding: 5px; "
                         "}");
    title->setStyleSheet("QLabel { color: rgb(145, 145, 145); }");  // 红色

    // 将滚动区域添加到布局
    layout->addWidget(title,0,Qt::AlignLeft|Qt::AlignTop);
    layout->addWidget(scrollArea);
}

QString TimelineChart::calculateRemainingTime()
{
    int remainingSeconds = QDateTime::currentSecsSinceEpoch() - m_startTime.currentSecsSinceEpoch();

    if (remainingSeconds < 0) {
        return "已过期";
    }
    int min = (m_countdown - remainingSeconds) / (1000*60);

    return QString("剩余%1分钟")
        .arg(min);
}

void Timeline::setEventSpacing(int spacing)
{
    eventSpacing = spacing;
    updateSize(); // 调整大小
}

void Timeline::setTopMargin(int margin)
{
    topMargin = margin;
    updateSize(); // 调整大小
}

void Timeline::clearEvents()
{
    events.clear();  // 清空事件列表
    updateSize();    // 调整控件大小
    update();        // 触发重绘
}

void Timeline::updateSize()
{
    int totalHeight = topMargin + events.size() * eventSpacing;
    resize(width(), totalHeight); // 调整控件的大小
}
